package cn.lili.controller.member;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.order.order.entity.vo.OrderItemVO;
import cn.lili.modules.payment.kit.CashierSupport;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.transfer.entity.Transfer;
import cn.lili.modules.transfer.entity.vo.TransferQueryVO;
import cn.lili.modules.transfer.entity.vo.TransferVO;
import cn.lili.modules.transfer.service.TransferService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.vo.RechargeVO;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.wallet.service.MemberWithdrawItemService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * create by yudan on 2022/7/22
 */
@RestController
@Api(tags = "平台端,会员转账接口")
@RequestMapping("/manager/member/transfer")
public class TransferManagerController {
	@Autowired
	private CashierSupport cashierSupport;
	@Autowired
	private TransferService transferService;
	@Autowired
	private MemberService memberService;

	@Autowired
	private MemberWalletService memberWalletService;

	@Autowired
	private RegionService regionService;

	@Autowired
	private MemberWithdrawItemService memberWithdrawItemService;

	@ApiOperation(value = "查询转账列表")
	@GetMapping
	public ResultMessage<IPage<TransferVO>> queryMineOrder(PageVO pageVO, TransferVO transferVO) {
		QueryWrapper<TransferVO> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(StringUtils.isNotEmpty(transferVO.getPaymentWallet()), "t.payment_wallet",
				transferVO.getPaymentWallet());
		queryWrapper.eq("t.state", "success");
		// 付款人
		queryWrapper.eq(StringUtils.isNotEmpty(transferVO.getPayer()), "t.payer", transferVO.getPayer());
		queryWrapper.eq(StringUtils.isNotEmpty(transferVO.getMemberId()), "t.payer", transferVO.getMemberId());
		// 时间查询
		if (StringUtils.isNotEmpty(transferVO.getStartTime()) && StringUtils.isNotEmpty(transferVO.getEndTime())) {
			queryWrapper.le("DATE_FORMAT(t.payment_time,'%Y-%m-%d')", transferVO.getEndTime());
			queryWrapper.ge("DATE_FORMAT(t.payment_time,'%Y-%m-%d')", transferVO.getStartTime());
		}
		// 收款人手机号
		queryWrapper.eq(StringUtils.isNotEmpty(transferVO.getPayeePhone()), "t.payee_phone",
				transferVO.getPayeePhone());
		// 收款人级别
		queryWrapper.eq(StringUtils.isNotEmpty(transferVO.getPayeeGradeName()), "mc.name",
				transferVO.getPayeeGradeName());
		// 区域
		if (StringUtils.isNotEmpty(transferVO.getRegionId())) {
			List list = regionService.getItemAdCod(transferVO.getRegionId());
			queryWrapper.in(CollectionUtils.isNotEmpty(list), "m.location", list);
		}
		queryWrapper.orderByDesc("payment_time");
		IPage<TransferVO> transferIPage = transferService.queryList(PageUtil.initPage(pageVO), queryWrapper);
		return ResultUtil.data(transferIPage);
	}

	@ApiOperation(value = "查询转账列表")
	@RequestMapping(value = "/list")
	public ResultMessage<IPage<Map>> queryMineOrder(PageVO pageVO, TransferQueryVO transferQueryVO) {
		// AuthUser authUser = Objects.requireNonNull(UserContext.getCurrentUser());
		// AuthUser authUser=null;
		// if (authUser == null) {
		// throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
		// }
		QueryWrapper<TransferQueryVO> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("lt.state", "success");
		if (StringUtils.isNotEmpty(transferQueryVO.getLocation())) {
			List list = regionService.getItemAdCod(transferQueryVO.getLocation());
			queryWrapper.in(list.size() > 0, "lm.location", list);
			queryWrapper.and(qw -> qw.in("lm1.location", list).or().eq("lm1.location", list));

		}
		queryWrapper.eq(StringUtils.isNotEmpty(transferQueryVO.getSn()), "lt.sn", transferQueryVO.getSn());
		if (StringUtils.isNotEmpty(transferQueryVO.getMobile()))
			queryWrapper.and(qw -> qw.eq("lm1.mobile", transferQueryVO.getMobile()).or().eq("lm2.mobile",
					transferQueryVO.getMobile()));
		if (StringUtils.isNotEmpty(transferQueryVO.getLevel()))
			queryWrapper.and(qw -> qw.eq("lmc1.level", transferQueryVO.getLevel()).or().eq("lmc1.leve",
					transferQueryVO.getLevel()));
		queryWrapper.eq(StringUtils.isNotEmpty(transferQueryVO.getLevel()), "lmc.level", transferQueryVO.getLevel());
		if (StringUtils.isNotEmpty(transferQueryVO.getRoleName())) {
			UserEnums userEnums = UserEnums.valueOf(transferQueryVO.getRoleName());
			queryWrapper.and(qw -> qw.eq("lro1.name", userEnums.getRole()).or().eq("lro2.name", userEnums.getRole()));
		}
		queryWrapper.between(
				StringUtils.isNotEmpty(transferQueryVO.getStartDate())
						&& StringUtils.isNotEmpty(transferQueryVO.getEndDate()),
				"lt.payment_time", transferQueryVO.getStartDate(), transferQueryVO.getEndDate());
		queryWrapper.and(wrapper -> wrapper.isNull("lt.type").or().notIn("lt.type", "PORT_FEE"));
		queryWrapper.isNotNull("lm1.id");
		queryWrapper.groupBy("lt.sn");
		queryWrapper.orderByDesc("lt.payment_time");

		IPage<Map> transferIPage = transferService.queryByParamsAdmin(PageUtil.initPage(pageVO), queryWrapper);
		if (transferIPage != null && transferIPage.getRecords().size() > 0) {
			for (Map m : transferIPage.getRecords()) {
				if (!StringUtils.equals("", m.get("zLocation").toString()))
					m.put("zLocationName", regionService.getItemAdCodOrName(StringUtils.toString(m.get("zLocation"))));
				if (!StringUtils.equals("", m.get("slocation").toString()))
					m.put("sLocationName", regionService.getItemAdCodOrName(StringUtils.toString(m.get("slocation"))));
			}
		}
		return ResultUtil.data(transferIPage);
	}

	@RequestMapping(value = "/tradeDetail")
	@ApiOperation(value = "获取支付详情(转账)")
	public ResultMessage payment(Double price, String owner, String mobile) {

		QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("m.mobile", mobile);
		queryWrapper.orderByAsc("c.LEVEL");
		queryWrapper.last("limit 1");
		MemberVO memberVO = memberService.findByPhone(queryWrapper);
		// 添加订单
		Transfer transfer = new Transfer();
		transfer.setPayee(memberVO.getId());
		transfer.setPayeeCard(memberVO.getGradeName());
		transfer.setPayeeName(memberVO.getNickName());
		transfer.setPayeePhone(mobile);
		transfer.setPayeeImg(memberVO.getFace());
		transfer.setTransferMoney(price);
		transfer.setPaymentWallet(owner);
		transfer.setPayer("admin");
		String sn = SnowFlake.createStr("Z");
		transfer.setSn(sn);
		Member payee = memberService.getById(transfer.getPayee());// 收款人
		MemberWallet to = memberWalletService.getMemberWalletInfo(payee.getId(), WalletOwnerEnum.RECHARGE.name());
		MemberWallet from = memberWalletService.getMemberWalletInfo("admin", owner, "平台");

		memberWalletService.transferPay(sn, from, to, price, 0D, "TRANSFER");
		transfer.setPaymentTime(new Date());
		transfer.setState("success");
		transferService.save(transfer);
		return ResultUtil.data(transfer);
	}

	@ApiOperation(value = "扣率信息详情")
	@RequestMapping("/getFeeList")
	public ResultMessage<IPage<OrderItemVO>> getFeeList(PageVO page, String sn) {
		// 构建查询 返回数据
		IPage<OrderItemVO> orderItemVOIPage = memberWithdrawItemService.findItemByTransferSn(page, sn);
		return ResultUtil.data(orderItemVOIPage);
	}

}
